import {ref, reactive, watch} from "vue";
import {getSongById} from "@/api/api.ts";
// import type {songType} from "@/types/pageTypes/songs.ts";

type songKey = string | number | boolean | undefined;
import useStore from "@/pinia/index.ts";
// import {songClass} from "@/class/song.ts";
import {message} from "ant-design-vue";

export default function usePlayer() {
    const {user, songStore} = useStore();
    const loginType: string = user.loginType(); // 登录方式pc/mobile
    let computedCurrentTimeTimer: number | undefined; // 计算当前时间的计时器
    const audioRef = ref();
    let currentTime = ref<number>(0); //当前播放时长
    let durationTime = ref<number>(0); // 歌曲总时长
    let currentMUsicLyric = reactive<{ [key: number]: string }>({}); // 当前播放歌曲的歌词
    let songKeys = ref<string[]>([]);
    let currentVolume = ref<number>(0); // 当前音量
    let playingFlag = ref<boolean>(false);
    // const song = reactive<songType>(new songClass(0, '未知'));
    const {song} = songStore
    const getSongUrl = (url: songKey): string => {
        // 获取歌曲播放地址
        return import.meta.env.VITE_APP_BASE_SERVER + url;
    };
    // 获取歌曲详情
    const getSongDetail = async (id: number) => {
        let result = await getSongById(id)
        if (!result) return
        if (typeof result.data.lyric === 'string') {
            filterLrc(result.data.lyric); //解析歌词为keyvalue形式
        }

        songStore.setSongDetail(result.data)
        currentTime.value = 0;
        audioRef.value?.removeEventListener('loadedmetadata', handleLoadedMetadata);
        audioRef.value?.addEventListener('loadedmetadata', handleLoadedMetadata);

    };
    const handleLoadedMetadata = () => {
        if (!audioRef.value) {
            console.error('audioRef is not initialized');
            return;
        }

        const duration = audioRef.value.duration;
        if (typeof duration === 'number' && !isNaN(duration)) {
            durationTime.value = Math.floor(duration);
        } else {
            console.warn('Invalid or undefined duration:', duration);
            durationTime.value = 0;
        }
    };

    // 转换歌词
    const filterLrc = (values: string) => {
        // let lrc: { [key: string]: string } = {};
        let lyrics = values.split("\n");
        for (let i = 0; i < lyrics.length; i++) {
            let lyric = decodeURIComponent(lyrics[i]);
            let timeReg = /\[\d*:\d*((\.|\:)\d*)*\]/g;
            let timeRegArr = lyric.match(timeReg);
            if (!timeRegArr) continue; //跳过null
            //获取时间
            let clause = lyric.replace(timeReg, "");
            if (clause != "") {
                for (let k = 0, h = timeRegArr.length; k < h; k++) {
                    let t = timeRegArr[k];
                    //正则匹配
                    let min = Number(String(t.match(/\[\d*/i)).slice(1));
                    let sec = Number(String(t.match(/\:\d*/i)).slice(1));
                    //完整时间
                    let time = min * 60 + sec;
                    currentMUsicLyric[time] = clause;
                }
            }
        }
        getSongKeys(currentMUsicLyric);
    };
    const getSongKeys = (lrcArr: { [key: string | number]: string }) => {
        for (let key in lrcArr) {
            songKeys.value.push(key);
        }
    };
    // 时间转换
    const transTime = (seconds: number): string => {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${String(minutes).padStart(2, "0")}:${String(
            remainingSeconds
        ).padStart(2, "0")}`;
    };
    // 音量控制
    const setVolumn = (volumn: number): void => {
        const audioElement = document.getElementById("audioId"); // 获取audio Dom
        if (audioElement instanceof HTMLAudioElement) {
            audioElement.volume = parseFloat((volumn / 100).toFixed(2));
        }
    };
    const getVolumn = (): void => {
        const audioElement = document.getElementById("audioId"); // 获取audio Dom
        if (audioElement instanceof HTMLAudioElement) {
            currentVolume.value = audioElement.volume;
        } else {
            currentVolume.value = 0; // 默认值
        }
    };
    // 播放暂停控制
    const toPlay = () => {
        if (song.id) {
            playingFlag.value = !playingFlag.value;
            if (audioRef.value.paused) {
                audioRef.value.play();
            } else {
                audioRef.value.pause();
            }
        } else {
            message.warning('请先选择播放的歌曲')
        }

    };
    const changeCurrentTime = (time: number): void => {
        currentTime.value = time;
        audioRef.value.currentTime = time;
        // playingFlag.value = true;
    };
    const displayTimeFormatter = (currentTime: number): string => {
        return transTime(currentTime);
    };
    watch(
        () => playingFlag.value,
        (newV) => {
            if (newV) {
                computedCurrentTimeTimer = window.setInterval(() => {
                    if (currentTime.value === durationTime.value) {
                        clearInterval(computedCurrentTimeTimer);
                        computedCurrentTimeTimer = undefined;
                    } else {
                        durationTime.value = parseInt(audioRef.value.duration || 0);
                        currentTime.value = parseInt(audioRef.value.currentTime || 0);
                    }
                }, 1000);
            } else {
                if (computedCurrentTimeTimer !== undefined) {
                    clearInterval(computedCurrentTimeTimer);
                    computedCurrentTimeTimer = undefined;
                }
            }
        }
    );
    return {
        // song,
        playingFlag,
        currentTime,
        durationTime,
        currentVolume,
        audioRef,
        songKeys,
        loginType,
        currentMUsicLyric,
        getSongUrl,
        toPlay,
        transTime,
        setVolumn,
        getVolumn,
        getSongDetail,
        changeCurrentTime,
        displayTimeFormatter
    };
}


